﻿using System;
using System.Web.Mvc;
using System.ComponentModel;

namespace BlueSky.Web.Binders
{
    /// <summary>
    /// Http cookie binder attribute.
    /// </summary>
    public class HttpCookieBinderAttribute : CustomModelBinderAttribute
    {
        /// <summary>
        /// Cookie name.
        /// </summary>
        public string CookieName { get; set; }

        /// <summary>
        /// Cookie key
        /// </summary>
        public string Key { get; set; }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="cookieName">Cookie name.</param>
        /// <param name="key">Cookie key.</param>
        public HttpCookieBinderAttribute(string cookieName, string key)
        {
            CookieName = cookieName;
            Key = key;
        }

        public override IModelBinder GetBinder()
        {
            return new HttpCookieModelBinder(CookieName, Key);
        }
    }

    internal class HttpCookieModelBinder : ModelBinderBase
    {
        public string CookieName { get; set; }

        public string Key { get; set; }

        public HttpCookieModelBinder(string cookieName, string key)
        {
            CookieName = cookieName;
            Key = key;
        }
        
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string value = controllerContext.HttpContext.Request.Cookies[CookieName][Key];

            object model;
            if (bindingContext.ModelType == typeof(string))
            {
                model = value;
            }
            else
            {
                model = TypeDescriptor.GetConverter(bindingContext.ModelType).ConvertFromString(value);
            }

            return model;
        }
    }
}
